package app

import (
	"context"
	"fmt"

	"myproject/internal/browser"
)

// App struct - Wails 应用结构体
type App struct {
	ctx      context.Context
	browser  *browser.Browser
}

// NewApp creates a new App application struct
func NewApp() *App {
	return &App{
		browser: browser.NewBrowser(true), // 默认无头模式
	}
}

// Startup is called when the app starts. The context is saved
// so we can call the runtime methods
func (a *App) Startup(ctx context.Context) {
	a.ctx = ctx
}

// SetHeadless 设置是否使用无头模式
func (a *App) SetHeadless(headless bool) {
	a.browser.SetHeadless(headless)
}

// Greet returns a greeting for the given name
func (a *App) Greet(name string) string {
	return fmt.Sprintf("Hello %s, It's show time!", name)
}

// OpenBrowserAndScreenshot 打开浏览器，访问指定URL并截图保存
func (a *App) OpenBrowserAndScreenshot(url string, savePath string) (string, error) {
	ctx, cancel := a.browser.CreateContext()
	defer cancel()
	return browser.Screenshot(ctx, url, savePath)
}

// ClickElement 点击指定元素
func (a *App) ClickElement(url string, selector string, selectorType string) (string, error) {
	ctx, cancel := a.browser.CreateContext()
	defer cancel()
	return browser.ClickElement(ctx, url, selector, selectorType)
}

// InputText 在指定输入框中输入文本
func (a *App) InputText(url string, selector string, text string, selectorType string) (string, error) {
	ctx, cancel := a.browser.CreateContext()
	defer cancel()
	return browser.InputText(ctx, url, selector, text, selectorType)
}

// ExecuteJavaScript 执行 JavaScript 代码并返回结果
func (a *App) ExecuteJavaScript(url string, jsCode string) (string, error) {
	ctx, cancel := a.browser.CreateContext()
	defer cancel()
	return browser.ExecuteJavaScript(ctx, url, jsCode)
}

// GetPageTitle 获取页面标题
func (a *App) GetPageTitle(url string) (string, error) {
	ctx, cancel := a.browser.CreateContext()
	defer cancel()
	return browser.GetPageTitle(ctx, url)
}

// GetElementText 获取指定元素的文本内容
func (a *App) GetElementText(url string, selector string, selectorType string) (string, error) {
	ctx, cancel := a.browser.CreateContext()
	defer cancel()
	return browser.GetElementText(ctx, url, selector, selectorType)
}

// WaitForElement 等待指定元素出现
func (a *App) WaitForElement(url string, selector string, selectorType string, timeoutSeconds int) (string, error) {
	ctx, cancel := a.browser.CreateContext()
	defer cancel()
	return browser.WaitForElement(ctx, url, selector, selectorType, timeoutSeconds)
}

